package com.promise.jokerdream.response.parser

import com.promise.jokerdream.response.phone.FightTowerXmlResponse
import com.promise.jokerdream.utils.UrlFixer
import org.jsoup.Jsoup

/**
 * 斗神塔XML解析器
 * 专门用于解析大乐斗斗神塔相关的XML数据
 * 基于Jsoup实现
 */
class FightTowerXmlParser : BaseXmlParser<FightTowerXmlResponse>() {
    
    /**
     * 解析斗神塔XML数据
     * @param xmlString XML字符串
     * @return 解析结果
     */
    fun parseFightTowerXml(xmlString: String): XmlParseResult<FightTowerXmlResponse> {
        return parseXml(xmlString)
    }
    
    /**
     * 实现基类的具体解析逻辑
     * @param xmlString XML字符串
     * @return 解析后的斗神塔数据
     */
    override fun doParse(xmlString: String): FightTowerXmlResponse {
        return try {
            // 统一替换<br />为<br/>，确保Jsoup能正确识别
            val normalizedXml = xmlString.replace(Regex("<br\\s*/?>"), "<br/>")
            val doc = Jsoup.parse(normalizedXml)
            val divElement = doc.selectFirst("div#id")
            
            if (divElement != null) {
                parseTowerContent(divElement)
            } else {
                FightTowerXmlResponse()
            }
        } catch (e: Exception) {
            FightTowerXmlResponse()
        }
    }
    
    /**
     * 解析斗神塔内容
     */
    private fun parseTowerContent(divElement: org.jsoup.nodes.Element): FightTowerXmlResponse {
        
        // 获取第一个和第二个<br/>之间的内容作为actionResult
        val actionResult = extractActionResult(divElement)
        
        // 解析链接
        val links = divElement.select("a")
        val linkMap = mutableMapOf<String, String>()
        links.forEach { link ->
            val href = link.attr("href")
            val text = link.text().trim()
            when {
                text.contains("开始挑战") -> linkMap["startChallenge"] = href
                text.contains("挑战下一层") -> linkMap["nextFloor"] = href
                text.contains("结束挑战") -> linkMap["endChallenge"] = href
                text.contains("自动挑战") -> linkMap["autoChallenge"] = href
                text.contains("复活") -> linkMap["revive"] = href
            }
        }
        
        // 解析文本信息
        val textContent = divElement.text()
        
        // 解析当前挑战信息
        val currentFloor = extractIntFromText(textContent, "第", "层")
        val currentScore = extractIntFromText(textContent, "第\\d+层 ", "分")
        val remainingReviveCount = extractIntFromText(textContent, "剩余复活次数：", " ")
        val remainingBattleTime = extractIntFromText(textContent, "战斗剩余时间：", "\\n")
        
        // 解析挑战次数信息
        val todayCountMatch = Regex("今日剩余次数：(\\d+)/(\\d+)").find(textContent)
        val todayRemainingCount = todayCountMatch?.groupValues?.get(1)?.toIntOrNull() ?: 0
        val todayTotalCount = todayCountMatch?.groupValues?.get(2)?.toIntOrNull() ?: 0
        
        val weeklyCountMatch = Regex("本周付费次数：(\\d+)/(\\d+)").find(textContent)
        val weeklyPaidCount = weeklyCountMatch?.groupValues?.get(1)?.toIntOrNull() ?: 0
        val weeklyPaidTotalCount = weeklyCountMatch?.groupValues?.get(2)?.toIntOrNull() ?: 0
        
        return FightTowerXmlResponse(
            actionResult = actionResult,
            startChallengeUrl = UrlFixer.fixUrl(linkMap["startChallenge"] ?: ""),
            nextFloorUrl = UrlFixer.fixUrl(linkMap["nextFloor"] ?: ""),
            endChallengeUrl = UrlFixer.fixUrl(linkMap["endChallenge"] ?: ""),
            autoChallengeUrl = UrlFixer.fixUrl(linkMap["autoChallenge"] ?: ""),
            reviveUrl = UrlFixer.fixUrl(linkMap["revive"] ?: ""),
            currentFloor = currentFloor,
            currentScore = currentScore,
            remainingReviveCount = remainingReviveCount,
            remainingBattleTime = remainingBattleTime,
            todayRemainingCount = todayRemainingCount,
            todayTotalCount = todayTotalCount,
            weeklyPaidCount = weeklyPaidCount,
            weeklyPaidTotalCount = weeklyPaidTotalCount
        )
    }
    
    /**
     * 从文本中提取整数
     */
    private fun extractIntFromText(text: String, prefix: String, suffix: String): Int {
        val pattern = if (suffix == "\\n") {
            "$prefix(\\d+)".toRegex()
        } else {
            "$prefix(\\d+)$suffix".toRegex()
        }
        return pattern.find(text)?.groupValues?.get(1)?.toIntOrNull() ?: 0
    }
    
    /**
     * 提取第一个和第二个<br/>之间的内容作为操作结果
     */
    private fun extractActionResult(divElement: org.jsoup.nodes.Element): String {
        val html = divElement.html()
        
        // 直接使用<br/>进行分割，与其他解析器保持一致
        val parts = html.split(Regex("<br\\s*/?>"))
        
        // 取第一个和第二个<br/>中间的文案（索引1）
        if (parts.size >= 2) {
            val content = parts[1].trim()
            // 移除HTML标签，只保留文本
            val doc = Jsoup.parse(content)
            return doc.text()
                .trim()
        }
        
        return ""
    }
}
